<template>
  <div :class="bem.b('body')">
    <div
      :class="bem.b('row')"
      v-for="(item, rowIndex) in tableData"
      :key="item.__id__"
      :style="{
        gridTemplateColumns:
          tableContext?.gridTemplateColumnsStyle.value,
      }"
    >
      <div
        :class="[bem.b('column'), bem.is('extra', config.extra)]"
        v-for="(config, i) in columnConfigs"
        :key="Math.random() + i"
      >
        <TableColumnWrapper
          :data="{
            data: tableData,
            index: rowIndex,
            row: tableData[rowIndex],
          }"
          :config="config"
          :state="tableContext?.states.value[rowIndex]"
          @edit="handleEdit(rowIndex)"
          @save="handleSave(rowIndex)"
          @add="handleAdd(rowIndex)"
          @del="handleDel(rowIndex)"
          @copy="handleCopy(rowIndex)"
        ></TableColumnWrapper>
      </div>
    </div>
    <!-- {{ tableData }} -->
  </div>
</template>

<script setup lang="ts">
import { inject, nextTick, ref } from 'vue';
import { tableContextInjectKey } from '../table/table';
import { easyTableColumnKey } from '../../../easy-table/src/constant';
import { createNamespace } from '../libs/bem';

import TableColumnWrapper from '../table-column/table-column-wrapper';
import type { DataSourceItem } from '../libs/data-source';

defineOptions({ name: 'extra-table-body' });
const bem = createNamespace('extra-table');

const tableContext = inject(tableContextInjectKey, undefined);
console.log('🚀 ~ tableContext:', tableContext);

// let easyTableColumnExpand;
// nextTick(() => {
//   easyTableColumnExpand = inject(easyTableColumnKey, undefined);
//   console.log('🚀 ~ easyTableColumnExpand:', easyTableColumnExpand);
// });

const tableData = (tableContext?.dataSource ||
  []) as DataSourceItem[];

const columnConfigs = tableContext?.columns || ref([]);
// console.log('🚀 ~ columnConfigs:', columnConfigs);

const handleEdit = (index: number) => {
  // console.log('🚀 handleEdit', index);
  tableContext?.edit(index);
};
const handleSave = (index: number) => {
  // console.log('🚀 handleSave', index);
  tableContext?.save(index);
};

const handleAdd = (index: number) => {
  // console.log('🚀 handleAdd', index);
  tableContext?.add();
};
const handleDel = (index: number) => {
  // console.log('🚀 handleDel', index);
  tableContext?.del(index);
};
const handleCopy = (index: number) => {
  // console.log('🚀 handleCopy', index);
  tableContext?.copy(index);
};
</script>

<style scoped></style>
